//mysql数据库配置:
let mysql = require('mysql');
let connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: 'root',
    database: 'blog'
})
connection.connect()

module.exports = {

    //新增信息的查询:
    addArticle: (newArticle, cb) => {
        //sql语句:
        let sqlStr = 'insert into articles set ?';
        connection.query(sqlStr, newArticle, (err, results) => {
            //失败:
            if (err) return cb(err, null);
            //成功:
            cb(null, results);

        })
    },

    //详情页的信息查询:
    getDetail: (articleId, cb) => {

        //链表查询:
        let sqlStr = 'select articles.*, user.nickname from articles LEFT JOIN user ON articles.userId=user.id WHERE articles.id=?'

        //操作数据库:
        connection.query(sqlStr, articleId, (err, results) => {
            if (err) cb(err, null);
            cb(null, results)

        })
    },

    // 新建查询文章信息的model
    queryArticleById: (articleId, cb) => {
        let sqlStr = 'select * from articles where id=?'
        connection.query(sqlStr, [articleId], (err, results) => {
            if (err) return cb(err, null)
            cb(null, results)
        })
    },

    //编辑文章的model
    updateArticleById: (article, cb) => {
        let sqlStr = 'update articles set title=?, content=?, ctime=? where id=?'
        connection.query(sqlStr, [article.title, article.content, article.ctime, article.id], (err, results) => {
            if (err) return cb(err, null)
            cb(null, results)
        })
    }
}